import asyncio
import websockets as ws
from websockets import ConnectionClosed


async def hello():
    uri = "ws://localhost:8899"
    try:
        async with ws.connect(uri) as websocket:
            while True:
                try:
                    message = input("Enter a message: ")
                    await websocket.send(message)
                    response = await websocket.recv()
                    print("Received:", response)
                    await asyncio.sleep(1)
                except ConnectionClosed as e:
                    print(e.code)
                    if e.code == 1006:
                        print("restart")
                        await asyncio.sleep(2)
                        break
                    elif e.code == 1000:
                        print("客户端主动close")
                        return
                    else:
                        print("other")
                        return
    except ConnectionRefusedError as e:
        print(e)
        await asyncio.sleep(2)


asyncio.get_event_loop().run_until_complete(hello())
